<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="案件类别" prop="type">
        <el-input
          v-model="queryParams.type"
          placeholder="请输入案件类别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="案号" prop="caseNo">
        <el-input
          v-model="queryParams.caseNo"
          placeholder="请输入案号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="案件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入案件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="立案状态" prop="status">
        <el-input
          v-model="queryParams.status"
          placeholder="请输入立案状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="curName">
        <el-input
          v-model="queryParams.curName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位名称" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['demo:case:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['demo:case:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['demo:case:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['demo:case:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="caseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false"/>
      <el-table-column label="案号" align="center" prop="caseNo" />
      <el-table-column label="案件名称" align="center" prop="name" />
      <el-table-column label="受案时间" align="center" prop="sTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="立案时间" align="center" prop="iTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.iTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结案时间" align="center" prop="eTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.eTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:case:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['demo:case:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleGen(scope.row)"
            v-hasPermi="['demo:case:gen']"
          >文书制作</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改案件管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="165px">
        <el-tabs class="center-tabs">
          <el-tab-pane label="案件基本信息">
            <el-row>
              <el-col :span="8">
                <el-form-item label="案件年度" prop="year">
                  <el-date-picker clearable
                    @blur="genCaseNo()"
                    v-model="form.year"
                    type="year"
                    value-format="yyyy"
                    placeholder="请选择案件年度">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="案件序号" prop="no">
                  <el-input v-model="form.no" placeholder="请输入案件序号" @blur="genCaseNo()" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="案件类别" prop="type">
                  <el-select v-model="form.type" placeholder="请选择案件类别" @blur="genCaseNo()">
                    <el-option
                      v-for="dict in dict.type.demo_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="案号" prop="caseNo">
                  <el-input disabled v-model="form.caseNo" placeholder="请输入案号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="">
                  <el-tag type="warning"><i class="el-icon-warning-outline" /> 自动生成格式：青黄农（<案件类别>）〔<案件年度>〕<案件序号>号</el-tag>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-form-item label="案件名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入案件名称" />
              </el-form-item>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="案件承办人员" prop="user">
                  <el-input v-model="form.user" placeholder="请输入案件承办人员" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="案件承办人员联系方式" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入案件承办人员联系方式" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="受案时间" prop="sTime">
                  <el-date-picker clearable
                    v-model="form.sTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择受案时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="立案状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="dict in dict.type.demo_status"
                      :key="dict.value"
                      :label="dict.value"
                    >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="立案时间" prop="iTime">
                  <el-date-picker clearable
                    v-model="form.iTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择立案时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-form-item label="结案时间" prop="eTime">
                <el-date-picker clearable
                  v-model="form.eTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择结案时间">
                </el-date-picker>
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="简要案情" prop="descript">
                <el-input v-model="form.descript" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="违反条例" prop="broke">
                <el-input v-model="form.broke" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="罚则" prop="sub">
                <el-input v-model="form.sub" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="处罚决定" prop="subDecide">
                <el-input v-model="form.subDecide" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-row>

          </el-tab-pane>
          <el-tab-pane label="当事人信息">
            <el-form-item label="当事人类型" prop="curType">
              <el-radio-group v-model="form.curType">
                <el-radio-button
                  v-for="dict in dict.type.demo_cur_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-row v-show="form.curType=='1'">
              <el-col :span="12" >
                <el-form-item label="姓名" prop="curName">
                  <el-input v-model="form.curName" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12" >
                <el-form-item label="性别" prop="curSex">
                  <el-select v-model="form.curSex" placeholder="请选择性别">
                    <el-option
                      v-for="dict in dict.type.demo_cur_sex"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-show="form.curType=='1'">
              <el-col :span="12" >
                <el-form-item label="民族" prop="curNation">
                  <el-input v-model="form.curNation" placeholder="请输入民族" />
                </el-form-item>
              </el-col>
              <el-col :span="12" >
                <el-form-item label="出生日期" prop="curBirth">
                  <el-date-picker clearable
                    v-model="form.curBirth"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择出生日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-show="form.curType=='1'">
              <el-form-item label="身份证（其他有效证件）号码" prop="curIdcard">
                <el-input v-model="form.curIdcard" placeholder="请输入身份证（其他有效证件）号码" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='1'">
              <el-form-item label="工作单位和职务" prop="curOrg">
                <el-input v-model="form.curOrg" placeholder="请输入工作单位和职务" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='1'">
              <el-form-item label="住所" prop="curAddr">
                <el-input v-model="form.curAddr" placeholder="请输入住所" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='1'">
              <el-form-item label="联系电话" prop="curPhone">
                <el-input v-model="form.curPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='1'">
              <el-form-item label="字号名称" prop="curFontname">
                <el-input v-model="form.curFontname" placeholder="请输入字号名称" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='1'">
              <el-form-item label="统一社会信用代码（注册码）" prop="curNo">
                <el-input v-model="form.curNo" placeholder="请输入统一社会信用代码（注册码）" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='2'">
              <el-form-item label="单位名称" prop="orgName">
                <el-input v-model="form.orgName" placeholder="请输入单位名称" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='2'">
              <el-form-item label="法定代表人" prop="orgOwner">
                <el-input v-model="form.orgOwner" placeholder="请输入法定代表人" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='2'">
              <el-form-item label="统一社会信用代码" prop="orgNo">
                <el-input v-model="form.orgNo" placeholder="请输入统一社会信用代码" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='2'">
              <el-form-item label="联系电话" prop="orgPhone">
                <el-input v-model="form.orgPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-row>

            <el-row v-show="form.curType=='2'">
              <el-form-item label="住所" prop="orgAddr">
                <el-input v-model="form.orgAddr" placeholder="请输入住所" />
              </el-form-item>
            </el-row>
            
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    

    <!-- 添加或修改案件管理对话框 -->
    <el-dialog title="制作文书" :visible.sync="make" width="1200px" append-to-body>
      <el-table v-loading="makeLoading" :data="templateList" @selection-change="handleTemplateSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="模板名称" align="center" prop="name" />
        <el-table-column label="缩略图" align="center" prop="prePic" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.prePic" :width="50" :height="50"/>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="templateTotal>0"
        :total="templateTotal"
        :page.sync="templateQueryParams.pageNum"
        :limit.sync="templateQueryParams.pageSize"
        @pagination="getTemplateList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="makeSubmit">确 定</el-button>
        <el-button @click="makeCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCase, getCase, delCase, addCase, updateCase, make } from "@/api/demo/case";
import { listTemplate } from "@/api/demo/template";
import { listByIds } from "@/api/system/oss";

export default {
  name: "Case",
  dicts: ['demo_status', 'demo_cur_type', 'demo_cur_sex', 'demo_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 选中模板Oss数组
      templateOssIds: [],
      // 非单个禁用
      templateSingle: true,
      // 非多个禁用
      templateMultiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 案件管理表格数据
      caseList: [],
      // 总条数
      templateTotal: 0,
      // 文书模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 制作文书选中案件ID
      dataId: undefined,
      // 是否显示制作文书
      make: false,
      // 遮罩层
      makeLoading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        caseNo: undefined,
        name: undefined,
        status: undefined,
        curType: undefined,
        curName: undefined,
        orgName: undefined,
      },
      // 查询参数
      templateQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        year: [
          { required: true, message: "案件年度不能为空", trigger: "blur" }
        ],
        no: [
          { required: true, message: "案件序号不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "案件类别不能为空", trigger: "blur" }
        ],
        caseNo: [
          { required: true, message: "案号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "案件名称不能为空", trigger: "blur" }
        ],
        user: [
          { required: true, message: "案件承办人员不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "案件承办人员联系方式不能为空", trigger: "blur" }
        ],
        sTime: [
          { required: true, message: "受案时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "立案状态不能为空", trigger: "blur" }
        ],
        iTime: [
          { required: true, message: "立案时间不能为空", trigger: "blur" }
        ],
        eTime: [
          { required: true, message: "结案时间不能为空", trigger: "blur" }
        ],
        descript: [
          { required: true, message: "简要案情不能为空", trigger: "blur" }
        ],
        broke: [
          { required: true, message: "违反条例不能为空", trigger: "blur" }
        ],
        sub: [
          { required: true, message: "罚则不能为空", trigger: "blur" }
        ],
        subDecide: [
          { required: true, message: "处罚决定不能为空", trigger: "blur" }
        ],
        curType: [
          { required: true, message: "当事人类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 自动生成案号 */
    genCaseNo(){
      console.log(1)
      let typeValue = this.form.type;
      const typeName = this.dict.type.demo_type.find(function(item,index,arr){
        return item.value == typeValue;
      })
      this.form.caseNo = "青黄农（" + typeName['label'] + "）〔" + this.form.year + "〕" + this.form.no + "号"
    },
    /** 查询案件管理列表 */
    getList() {
      this.loading = true;
      listCase(this.queryParams).then(response => {
        this.caseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询文书模板管理列表 */
    getTemplateList() {
      this.makeLoading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.templateTotal = response.total;
        this.makeLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 制作文书取消按钮
    makeCancel() {
      this.make = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        version: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        delFlag: undefined,
        year: undefined,
        no: undefined,
        type: undefined,
        caseNo: undefined,
        name: undefined,
        user: undefined,
        phone: undefined,
        sTime: undefined,
        status: undefined,
        iTime: undefined,
        eTime: undefined,
        descript: undefined,
        broke: undefined,
        sub: undefined,
        subDecide: undefined,
        curType: undefined,
        curName: undefined,
        curSex: undefined,
        curNation: undefined,
        curBirth: undefined,
        curIdcard: undefined,
        curOrg: undefined,
        curAddr: undefined,
        curPhone: undefined,
        curFontname: undefined,
        curNo: undefined,
        orgName: undefined,
        orgOwner: undefined,
        orgNo: undefined,
        orgPhone: undefined,
        orgAddr: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 多选框选中数据
    handleTemplateSelectionChange(selection) {
      this.templateOssIds = selection.map(item => item.file)
      this.templateSingle = selection.length!==1
      this.templateMultiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.curType = "1";
      this.open = true;
      this.title = "添加案件管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCase(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改案件管理";
      });
    },
    /** 文书制作 */
    handleGen(row) {
      this.dataId = row.id;
      this.getTemplateList();
      this.make = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          let typeValue = this.form.type;
          const typeName = this.dict.type.demo_type.find(function(item,index,arr){
            return item.value == typeValue;
          })
          this.form.caseNo = "青黄农（" + typeName['label'] + "）〔" + this.form.year + "〕" + this.form.no + "号"
          if (this.form.id != null) {
            updateCase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 制作文书提交按钮 */
    makeSubmit() {
      listByIds(this.templateOssIds).then(response => {
        const templateOssUrls = response.data.map(item => item.url).join(",");
        const templateNames = response.data.map(item => item.originalName).join(",");
        make({
          caseId: this.dataId,
          templateOssUrls: templateOssUrls,
          templateNames: templateNames
        }).then(response=>{
          let excel = new Blob([response])
          let url = URL.createObjectURL(excel)
          let a = document.createElement("a")
          a.href = url
          a.download = "制作文书.zip"
          a.click()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除案件管理编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCase(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/case/export', {
        ...this.queryParams
      }, `case_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
